package com.flyco.modules.task.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.DateConverter;

import java.util.TimeZone;

/**
 * @Author hui_li
 * @Date 2024/2/2 17:18
 * @Version 1.0
 */
public class XStreamXmlBeanUtil {
    /**
     * JavaBean转XML
     *
     * @param bean - JavaBean
     * @return - XML
     */
    public static String toXml(Object bean) {
        return initXStream(bean.getClass()).toXML(bean);
    }

    /**
     * XML转JavaBean
     *
     * @param xml       - XML
     * @param beanClazz - JavaBean Class
     * @param <T>
     * @return - JavaBean
     */
    @SuppressWarnings("unchecked")
    public static <T> T fromXml(String xml, Class<T> beanClazz) {
        return (T) initXStream(beanClazz).fromXML(xml);
    }

    private static XStream initXStream(Class<?> beanClazz) {
        XStream x = new XStream();
        x.registerConverter(new DateConverter("yyyy-MM-dd HH:mm:ss", null, TimeZone.getTimeZone("GMT+8")));

        //不使用默认的类加载器，需要手动设置类加载器
        x.setClassLoader(beanClazz.getClassLoader());
        x.processAnnotations(beanClazz);
        x.allowTypesByRegExp(new String[]{".*"});
        // 开起注解功能
        x.autodetectAnnotations(true);
        // 忽律未知字段
        x.ignoreUnknownElements();
        return x;
    }
}

